package ysq.xyg.recovery.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.iherus.codegen.qrcode.SimpleQrcodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import ysq.xyg.base.model.dto.ReturnEntity;
import ysq.xyg.base.service.impl.BaseServiceImpl;
import ysq.xyg.base.util.BaseConstant;
import ysq.xyg.base.util.BaseUtil;
import ysq.xyg.base.util.httpClient.HttpUtil;
import ysq.xyg.recovery.dao.RecoveryComplainDao;
import ysq.xyg.recovery.model.po.RecoveryComplain;
import ysq.xyg.recovery.model.vo.RecoveryComplainVo;
import ysq.xyg.recovery.service.PowerMemberService;
import ysq.xyg.recovery.service.RecoveryComplainService;
import ysq.xyg.sys.model.po.SysUser;
import ysq.xyg.web.model.po.WebMember;
import ysq.xyg.web.service.WebMemberService;
import ysq.xyg.wxapi.api.WxApiClient;
import ysq.xyg.wxapi.model.base.TemplateMessage;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 回收金模块-投诉表service实现
 *
 * @author congcong tao
 * @date 2019-7-30 20:19:27
 */
@Service("recoveryComplainService")
public class RecoveryComplainServiceImpl extends BaseServiceImpl<RecoveryComplain> implements RecoveryComplainService {

    @Autowired
    private PowerMemberService powerMemberService;
    @Resource
    private WebMemberService webMemberService;
    @Resource
    private RecoveryComplainDao recoveryComplainDao;

    private RecoveryComplain recoveryComplain;

    @Autowired
    public void setBaseDao(RecoveryComplainDao recoveryComplainDao) {
        this.baseDao = recoveryComplainDao;
    }

    /**
     * 分页查询
     *
     * @param recoveryComplainVo 对象
     * @param pageSize 展示数量
     * @param pageNum 当前页面
     * @return ReturnEntity 对象
     * @author congcong tao
     * @date 2019-7-30 20:19:27
     */
    @Override
    public ReturnEntity page(RecoveryComplainVo recoveryComplainVo, int pageSize, int pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        PageHelper.orderBy(" update_time desc");
        List<RecoveryComplain> list = acceptList(recoveryComplainVo);
        PageInfo<RecoveryComplain> page=new PageInfo<RecoveryComplain>(list);
        return new ReturnEntity(page.getList(),page.getTotal(),page.isHasNextPage());
    }

    @Override
    public ReturnEntity pageLeft(RecoveryComplainVo recoveryComplainVo, int pageSize, int pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        PageHelper.orderBy(" update_time desc");
        if (StringUtil.isNotEmpty(recoveryComplainVo.getMemberNickName())) {
            recoveryComplainVo.setMemberNickName(BaseUtil.encodeBase64String(recoveryComplainVo.getMemberNickName()));
        }
        List<RecoveryComplain> list = recoveryComplainDao.selectEntityList(recoveryComplainVo);
        if (list != null && list.size() > 0) {
            for (RecoveryComplain recoveryComplain : list) {
                if (StringUtils.isNotEmpty(recoveryComplain.getMemberNickName())) {
                    recoveryComplain.setMemberNickName(BaseUtil.decodeBase64(recoveryComplain.getMemberNickName()));
                }
                // 创建用户id二维码，有则创建，无则修改
            }
        }
        PageInfo<RecoveryComplain> page=new PageInfo<RecoveryComplain>(list);
        return new ReturnEntity(page.getList(),page.getTotal(),page.isHasNextPage());
    }

    /**
     * 修改
     *
     * @param recoveryComplainVo 对象
     * @param currentUser 当前用户
     * @return ReturnEntity 对象
     * @author congcong tao
     * @date 2019-7-30 20:19:27
     */
    @Override
    public ReturnEntity addOrUpdate(RecoveryComplainVo recoveryComplainVo, SysUser currentUser) {
        boolean isUpate=true;
        if(StrUtil.isEmpty(recoveryComplainVo.getId())){
            recoveryComplain=new RecoveryComplain(currentUser);
            isUpate=false;
        }else{
            recoveryComplain=selectByPrimaryKey(recoveryComplainVo.getId());
            if(ObjectUtil.isNull(recoveryComplain)){
                return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
            }
            recoveryComplain.setUpdateTime(new Date());
            recoveryComplain.setUpdateUser(currentUser.getId());
        }
        recoveryComplain.setMemberId(recoveryComplainVo.getMemberId());
        recoveryComplain.setComplainCode(recoveryComplainVo.getComplainCode());
        recoveryComplain.setCommunityName(recoveryComplainVo.getCommunityName());
        recoveryComplain.setName(recoveryComplainVo.getName());
        recoveryComplain.setPhone(recoveryComplainVo.getPhone());
        recoveryComplain.setContent(recoveryComplainVo.getContent());
        recoveryComplain.setImage(recoveryComplainVo.getImage());
        recoveryComplain.setStatus(recoveryComplainVo.getStatus());
        int num=0;
        if(isUpate){
            num=updateByPrimaryKey(recoveryComplain);
        }else{
            num=insert(recoveryComplain);
        }
        if(num<=0){
            return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
        }
        return new ReturnEntity();
    }

    @Override
    public ReturnEntity addOrUpdate(HttpServletRequest request, RecoveryComplainVo recoveryComplainVo) {
        boolean isUpate=true;
        if (StrUtil.isEmpty(recoveryComplainVo.getId())) {
            recoveryComplain = new RecoveryComplain();
            recoveryComplain.setId(BaseUtil.uId());
            recoveryComplain.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_NORMAL);
            recoveryComplain.setCreateTime(DateUtil.date());
            recoveryComplain.setUpdateTime(recoveryComplain.getCreateTime());
            isUpate=false;
        } else {
            recoveryComplain = selectByPrimaryKey(recoveryComplainVo.getId());
            if(ObjectUtil.isNull(recoveryComplain)){
                return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
            }
            recoveryComplain.setUpdateTime(new Date());
        }
        // 判断是否有二维码
        if (StringUtils.isNotEmpty(recoveryComplainVo.getMemberId())) {
            WebMember webMember = webMemberService.selectByPrimaryKey(recoveryComplainVo.getMemberId());
            String qrCode = getQrCode(request, webMember.getCardNo());
            recoveryComplain.setQrCode(qrCode);
        }
        recoveryComplain.setMemberId(recoveryComplainVo.getMemberId());
        recoveryComplain.setComplainCode(recoveryComplainVo.getComplainCode());
        recoveryComplain.setCommunityName(recoveryComplainVo.getCommunityName());
        recoveryComplain.setName(recoveryComplainVo.getName());
        recoveryComplain.setPhone(recoveryComplainVo.getPhone());
        recoveryComplain.setContent(recoveryComplainVo.getContent());
        recoveryComplain.setImage(recoveryComplainVo.getImage());
        recoveryComplain.setStatus(recoveryComplainVo.getStatus());
        int num = 0;
        if(isUpate){
            num=updateByPrimaryKey(recoveryComplain);
        }else{
            num=insert(recoveryComplain);
        }
        if(num<=0){
            return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
        }
        // 需要传递信息
        // 发出预约申请
        TemplateMessage templateMessage = new TemplateMessage();
        templateMessage.setUrl("");
        // 找到管理端预约人
       /* String openId = powerMemberService.selectOpenIdByType(BaseConstant.POWER_MEMBER_CARD);
        templateMessage.setOpenid(openId);
        templateMessage.setTemplateId("RjlsC46UYLHJbaA1LhARw43sCIHLjIMinZg2z4ZjvsA");
        Map<String,String> data=new HashMap<String, String>();
        data.put("first", "您有一个用户标贴申请");
        data.put("keyword1", recoveryComplain.getName());
        data.put("keyword2", recoveryComplain.getPhone());
        data.put("keyword3", DateUtil.formatDateTime(DateUtil.date()));
        data.put("keyword4", recoveryComplain.getContent());
        data.put("remark", "备注：请尽快查处理");
        templateMessage.setDataMap(data);
        WxApiClient.sendTempletNotice(templateMessage);*/
        return new ReturnEntity();
    }

    /**
     * 删除
     *
     * @param id 主键id
     * @param currentUser 当前用户
     * @return ReturnEntity 对象
     * @author congcong tao
     * @date 2019-7-30 20:19:27
     */
    @Override
    public ReturnEntity delete(String id, SysUser currentUser) {
        RecoveryComplain recoveryComplain=selectByPrimaryKey(id);
        if(recoveryComplain!=null){
            recoveryComplain.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_DELETE);
            recoveryComplain.setUpdateTime(new Date());
            recoveryComplain.setUpdateUser(currentUser.getId());
            int num=updateByPrimaryKey(recoveryComplain);
            if(num>0){
                return new ReturnEntity();
            }
        }
        return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
    }

    /**
     * 获取集合
     *
     * @param recoveryComplainVo 对象
     * @return List<BaseDict> BaseDict集合
     * @author congcong tao
     * @date 2019-7-30 20:19:27
     */
    @Override
    public List<RecoveryComplain> acceptList(RecoveryComplainVo recoveryComplainVo){
        Example example = new Example(RecoveryComplain.class);
        Example.Criteria criteria = example.createCriteria();
        if(StringUtil.isNotEmpty(recoveryComplainVo.getRemoveTag())){
            criteria.andEqualTo("removeTag",recoveryComplainVo.getRemoveTag());
        }
        if(StringUtil.isNotEmpty(recoveryComplainVo.getPhone())){
            criteria.andLike("phone", "%" + recoveryComplainVo.getPhone() + "%");
        }
        example.setOrderByClause(" update_time desc");
        return recoveryComplainDao.selectByExample(example);
    }

    private String getQrCode(HttpServletRequest request, String cardNo) {
        String qrCode = "";
        String realPath = HttpUtil.getRealPath(request);
        String path = realPath + "/upload/complain/" + cardNo + ".png";
        File dicFile = new File(realPath + "/upload/complain/");
        if  (!dicFile .exists()  && !dicFile .isDirectory()) {
            dicFile .mkdir();
        }
        try {
            OutputStream out = new FileOutputStream(path);
            new SimpleQrcodeGenerator().generate(cardNo).toStream(out);
            qrCode = "/upload/complain/" + cardNo + ".png";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return qrCode;
    }
}
